#pragma once
#include "Common.hpp"
#include "ThreadPool.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include <sys/wait.h>

using namespace LogModule;
using namespace ThreadPoolModule;
const static int defaultsockfd = -1;
const static int defaultbacklog = 8;
using func_t = std::function<void()>;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port, func_t func)
        : _listensockfd(defaultsockfd), _port(port), _isrunning(false), _func(func)
    {
    }

    void Init()
    {
        // 1.创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd:" << _listensockfd;

        // 2.绑定端口
        InetAddr local(_port);
        int n = bind(_listensockfd, local.NetAddrPtr(),local.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd:" << _listensockfd;

        // 3.设置socket状态为listen
        n = listen(_listensockfd, defaultbacklog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd:" << _listensockfd;
    }

    void Service(int sockfd, InetAddr &addr)
    {
        char buffer[1024];
        while (true)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer)-1);
            // n>0读取成功；n<0读取失败；n==0对端关闭，读到了文件结尾
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo_string = ">>";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << addr.StringAddr() << "退出了...";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::DEBUG) << addr.StringAddr() << "异常...";
                close(sockfd);
                break;
            }
        }
    }

    class ThreadData
    {
    public:
        ThreadData(int sockfd,InetAddr& addr,TcpServer* tsvr)
        :_sockfd(sockfd)
        ,_addr(addr)
        ,_tsvr(tsvr)
        {}
        
        int _sockfd;
        InetAddr _addr;
        TcpServer* _tsvr;
    };

    static void* Routine(void* args)//这里必须加static，否则参数会多一个隐含的this
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_tsvr->Service(td->_sockfd,td->_addr);
        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, CONV(peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }

            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "accept success,peer addr:" << addr.StringAddr();

            // version 0 单进程
            //Service(sockfd, addr);
            
            //version 1 多进程
            // pid_t id = fork();
            // if(id < 0)//创建子进程失败
            // {
            //     LOG(LogLevel::FATAL) << "fork error";
            //     exit(FORK_ERR);
            // }
            // else if(id == 0)//子进程
            // {
            //     //虽然子进程能看见_listensockfd，但我们不想让他访问
            //     close(_listensockfd);
            //     if(fork() > 0)
            //         exit(OK);//子进程直接退出，将任务交给孙子进程
                
            //     Service(sockfd,addr);
            //     exit(OK);//孙子进程变为孤儿进程，交给系统1来回收，不用我们操心
            // }
            // else//父进程
            // {
            //     close(sockfd);
            //     pid_t rid = waitpid(id,nullptr,0);
            //     (void)rid;
            // }

            //version 2 多线程
            // ThreadData* td = new ThreadData(sockfd,addr,this);//这个类专门存储线程需要的数据
            // pthread_t tid;
            // pthread_create(&tid,nullptr,Routine,td);

            //version 3 线程池
            ThreadPool<func_t>::GetInstance()->Enqueue([this,sockfd,&addr](){this->Service(sockfd,addr);});
        }
        _isrunning = false;
    }

    ~TcpServer() {}

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;

    func_t _func;
};
